package cn.ubeta.ar.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by liudengyong on 2017/2/14.
 */

public class FileUtils {

    /**
     * 复制文件
     * @param assetsName
     * @param filename
     */
    public static void copyAssetsFile(Context context, String assetsName, String filename) {
        try {
            InputStream is = context.getResources().getAssets() .open(assetsName);
            FileOutputStream fos = new FileOutputStream(filename);
            byte[] buffer = new byte[7168];
            int count;
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
            }
            fos.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从Assets读取BMP文件
     * @param context
     * @param name
     * @return
     */
    public static Bitmap readBitmapFromAssets(Context context, String name) {
        AssetManager man = context.getAssets();
        InputStream is = null;
        try {
            is = man .open(name);
            return BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 把Bitmap转Byte
     */
    public static byte[] bmp2Bytes(Bitmap bm){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }

}
